package com.cskaoyan.weixin.service;

import com.cskaoyan.bean.Keyword;
import com.cskaoyan.bean.User1;
import com.cskaoyan.mapper.KeywordMapper;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.weixin.bean.search.HistoryKeyword;
import com.cskaoyan.weixin.bean.search.SearchHistory;
import com.cskaoyan.weixin.bean.search.SearchIndexVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SearchWxServiceImpl implements SearchWxService {

    @Autowired
    KeywordMapper keywordMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public SearchIndexVO querySearchIndex() {

        List<Keyword> hotKeywordList = keywordMapper.queryHotKeywordList();

        Integer userId = getUserId();
        List<HistoryKeyword> historyKeywords = null;
        if (userId != null) {
            historyKeywords = keywordMapper.queryHistorySearchOfUser(userId);
        }

        SearchIndexVO searchIndexVO = new SearchIndexVO();
        searchIndexVO.setDefaultKeyword(hotKeywordList.get(0));
        searchIndexVO.setHotKeywordList(hotKeywordList);
        searchIndexVO.setHistoryKeywordList(historyKeywords);

        return searchIndexVO;
    }

    @Override
    public List<String> searchHelper(String keyword){
        keyword = "%" + keyword +"%";
        List<String> keywords = keywordMapper.selectKeywordsByKeyword(keyword);
        return keywords;
    }

    @Override
    public int createSearchHistory(String keyword) {
        int insert = 0;
        Integer userId = getUserId();
        if (userId != null){
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setUserId(userId);
            searchHistory.setKeyword(keyword);
            searchHistory.setFrom("wx");
            Date date = new Date();
            searchHistory.setAddTime(date);
            searchHistory.setUpdateTime(date);
            searchHistory.setDeleted(false);
            insert = keywordMapper.insertSearchHistory(searchHistory);
        }

        return insert;
    }

    @Override
    public int clearSearchHistory() {
        int delete = keywordMapper.deleteSearchHistoryByUserId(getUserId());
        return delete;
    }

    private Integer getUserId(){
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (principals != null) {
            User1 primaryPrincipal = (User1) principals.getPrimaryPrincipal();
            return primaryPrincipal.getId();
        }
        return null;
    }
}
